package app.keter.secruity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

public class JwtUserDetails implements UserDetails {
  private final String id;
  private final String username;
  private String password;
  private Collection<? extends GrantedAuthority> authorities;
  private Date lastPasswordResetDate = null;

  public JwtUserDetails(String id, String username, List<LinkedHashMap> roles) {
    this.id = id;
    this.username = username;
    this.authorities = rolesToAuthority(roles);
  }

  public JwtUserDetails(
      String id,
      String username,
      String password,
      Collection<? extends GrantedAuthority> authorities) {
    this.id = id;
    this.username = username;
    this.password = password;
    this.authorities = authorities;
  }

  public JwtUserDetails(
      String id,
      String username,
      String password,
      Collection<? extends GrantedAuthority> authorities,
      Date lastPasswordResetDate) {
    this.id = id;
    this.username = username;
    this.password = password;
    this.authorities = authorities;
    this.lastPasswordResetDate = lastPasswordResetDate;
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return authorities;
  }

  private Collection<? extends GrantedAuthority> rolesToAuthority(List<LinkedHashMap> roles) {
    Collection<SimpleGrantedAuthority> authorities = new ArrayList<>(roles.size());
    for (LinkedHashMap<String, String> role : roles) {
      authorities.add(new SimpleGrantedAuthority(role.get("authority")));
    }
    return authorities;
  }

  @JsonIgnore
  public String getId() {
    return id;
  }

  @JsonIgnore
  @Override
  public String getPassword() {
    return password;
  }

  @Override
  public String getUsername() {
    return username;
  }

  @JsonIgnore
  @Override
  public boolean isAccountNonExpired() {
    return true;
  }

  @JsonIgnore
  @Override
  public boolean isAccountNonLocked() {
    return true;
  }

  @JsonIgnore
  @Override
  public boolean isCredentialsNonExpired() {
    return true;
  }

  @JsonIgnore
  @Override
  public boolean isEnabled() {
    return true;
  }

  @JsonIgnore
  public Date getLastPasswordResetDate() {
    return lastPasswordResetDate;
  }
}
